package com.cssy.yd.logic.web;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.entity.BasicCompanyDO;
import com.cssy.yd.basic.entity.BasicModePaymentDO;
import com.cssy.yd.basic.service.IBasicCompanyService;
import com.cssy.yd.logic.entity.LogicFkDO;
import com.cssy.yd.logic.entity.LogicFkItemDO;
import com.cssy.yd.logic.entity.LogicFkReturnItemDO;
import com.cssy.yd.logic.entity.LogicPoDO;
import com.cssy.yd.logic.entity.LogicPoReturnDO;
import com.cssy.yd.logic.entity.LogicFkReturnDO;
import com.cssy.yd.logic.entity.LogicPoReturnItemDO;
import com.cssy.yd.logic.service.ILogicFkReturnService;
import com.cssy.yd.logic.service.ILogicPoReturnService;
import com.cssy.yd.logic.service.ILogicPoService;
import com.cssy.yd.basic.service.IBasicModePaymentService;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.exception.SyCodeException;

@Controller
@RequestMapping("/yd/logic/fkreturn")
public class FkReturnController extends BaseController<LogicFkReturnDO> {
	private static final Logger logger = Logger.getLogger(FkReturnController.class);
	private static final String MANAGER = "/yd/logic/fkreturn/FKReturnManager";// 列表页面
	private static final String EIDT = "/yd/logic/fkreturn/FkReturnOperation";// 添加、修改、显示页面
	

	
	@Resource(name = "logicFkReturnService")
	private ILogicFkReturnService logicFkReturnService;
	
	@Resource(name = "logicPoReturnService")
	private ILogicPoReturnService logicPoReturnService;
	
	@Resource(name="basicCompanyService")
	private IBasicCompanyService basicCompanyService;
	
	@Resource(name = "basicModePaymentService")
	private IBasicModePaymentService basicModePaymentService;
	
	@Resource(name = "logicPoService")
	private ILogicPoService logicPoService;

	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		String spcode =request.getParameter("spCode");
		String pid =request.getParameter("pid");
		if(StringUtils.isNotEmpty(spcode)){
			scs.addCondition("spcode", spcode, SearchCondition.OP_EQUAL);
		}else if(pid!=null&&!"".equals(pid)){
			scs.addCondition("spcode", pid,SearchCondition.OP_EQUAL);
		}
		String billStatus = request.getParameter("billStatus");
		if(StringUtils.isNotEmpty(billStatus)){
			if(StringUtils.equals(billStatus, "0"))
				scs.addCondition("billstatus", Integer.parseInt(billStatus), "=");	
			else
				scs.addCondition("billstatus", Integer.parseInt("0"),"!=");
		}
		
		scs.setOrderBy("dctime desc");
		SearchResult result= logicFkReturnService.findListByExample(scs);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/fkreturnlist")
	@ResponseBody
	public LogicFkReturnDO returnlist(HttpServletRequest request, Model model)
			throws Exception {
		String id=request.getParameter("id"); //logic_po_return.id
		String oricode=request.getParameter("oricode");   //采购退货单号
		String pocode = request.getParameter("pocode");  //采购订单号
		Double ythk = null;
		Double amount = Double.parseDouble("0.0");
		
		//设置查询历史退款单的条件
		SearchConditions scs = new SearchConditions();
		scs.addCondition("billstatus", "2", SearchCondition.OP_EQUAL);
		scs.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
		
		List<LogicPoReturnItemDO> poReturnItem=null;
		//设置按采购退货单id查询采购退货item的条件
		SearchConditions scs1 = new SearchConditions();
		scs1.addCondition("returnpoid", id, SearchCondition.OP_EQUAL);
		scs1.setRemovedProperty(null);
		scs1.setLimitPage(false);
		scs1.setOrderBy(null);
		
		LogicFkReturnDO fkreturnDO = new LogicFkReturnDO();
		
		List<LogicPoDO> polist = new ArrayList<LogicPoDO>();
		SearchResult sr = new SearchResult();
		SearchConditions scs2 = new SearchConditions();
		scs2.addCondition("pocode", pocode, SearchCondition.OP_EQUAL);
		
		try{
			poReturnItem=logicPoReturnService.findItemListByExample(scs1).getResults();; //按采购退货单id查询PoReturnItemDO的list
			for(LogicPoReturnItemDO poreturnitemDO : poReturnItem) {  //遍历退货单item得到退款单的总货款
				BigDecimal amount1 = new BigDecimal(poreturnitemDO.getPrice()==null? new Double("0.0"):poreturnitemDO.getPrice()).multiply(new BigDecimal(poreturnitemDO.getJreturnquantity()==null?new Double("0.0"):poreturnitemDO.getJreturnquantity()));
				amount = new BigDecimal(amount.toString()).add(amount1).doubleValue();
			}
			ythk = logicFkReturnService.findLastedDOByExample(scs); //最近一次退款之后退款单的已退金额
			sr = logicPoService.findListByExample(scs2);   //根据采购订单编号查询LogicPoDO,以获取币种和汇率
			if(sr.getRecordCount()>0) {
				polist = sr.getResults();
				fkreturnDO.setCurrency(polist.get(0).getCurrency());
				fkreturnDO.setExchangeRate(polist.get(0).getExchangeRate());
			} 
			if(ythk != null&&!"".equals(ythk) ){
				fkreturnDO.setYthk(ythk);
			} else {
				fkreturnDO.setYthk(Double.parseDouble("0.0"));
			}
			if(amount != null&&!"".equals(amount) ){
				fkreturnDO.setAmount(amount);
			} else {
				fkreturnDO.setAmount(Double.parseDouble("0.0"));
			}
		 } catch(Exception e) {
			 e.printStackTrace();
			 logger.error(e.getMessage(), e);
		 }		
		
		 return fkreturnDO;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/fkreturnitemlist")
	public void fkreturnitemlist(HttpServletRequest request, HttpServletResponse response, Model model)
			throws Exception {
		String id=request.getParameter("id"); //采购退货单id，等于logic_po_return_item.returnpoid，logic_po_return.id
		String oricode=request.getParameter("oricode");   //采购退货单号
		List<LogicPoReturnItemDO> poreturnitem=null; //当前选中的退货单item
		List<LogicFkReturnItemDO> fkreturnitem = new ArrayList<LogicFkReturnItemDO>();  //转换成对应的退款单item
		List<LogicFkReturnDO> historyfkreturn = new ArrayList<LogicFkReturnDO>();
		
		if(id!=null&&!"".equals(id)){
			//按采购退货单id查询采购退货item
			SearchConditions scs = new SearchConditions();
			scs.addCondition("returnpoid", id, SearchCondition.OP_EQUAL);
			scs.setRemovedProperty(null);
			scs.setLimitPage(false);
			scs.setOrderBy("code");
			poreturnitem=logicPoReturnService.findItemListByExample(scs).getResults();
		}
		
		if(oricode!=null&&!"".equals(oricode)) {	
			SearchConditions scs1 = new SearchConditions();
			SearchResult sr = new SearchResult();
			scs1.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
			scs1.addCondition("billstatus","2", SearchCondition.OP_EQUAL);
			//查找对应的所有历史退款单 按采购退货单(oricode)及单据状态为完结的(billstatus=2)来查
			sr = logicFkReturnService.findListByExample(scs1);
			if(sr.getRecordCount()>0){ //有退款记录
				historyfkreturn = sr.getResults();
				for (LogicPoReturnItemDO si : poreturnitem) {
					BigDecimal tempythk = new BigDecimal("0.0");
					Double ythk = Double.parseDouble("0.0");
					Double wthk = Double.parseDouble("0.0");
					LogicFkReturnItemDO li = new LogicFkReturnItemDO();
					li.setBatch(si.getBatch());
					li.setCode(si.getCode());  //物料编码
					li.setName(si.getName());
					li.setStatus(si.getState());
					li.setUnit(si.getJunit());
					li.setSpec(si.getSpec());
					li.setQuantity(si.getJreturnquantity());
					li.setTax_price(new BigDecimal(si.getPrice()==null? new Double("0.0"):si.getPrice()));
					li.setAmount(new BigDecimal(si.getPrice()==null? new Double("0.0"):si.getPrice()).multiply(new BigDecimal(si.getJreturnquantity()==null?new Double("0.0"):si.getJreturnquantity())).doubleValue());
					for(LogicFkReturnDO hisfk : historyfkreturn) { //历史退款单循环
						SearchConditions scs2 = new SearchConditions();
						SearchResult sr1 = new SearchResult();
						scs2.setRemovedProperty(null);
						scs2.addCondition("tkid", hisfk.getId(), SearchCondition.OP_EQUAL);
						scs2.addCondition("batch", li.getBatch(), SearchCondition.OP_EQUAL);
						scs2.addCondition("code",li.getCode(), SearchCondition.OP_EQUAL); 
						scs2.addCondition("status",li.getStatus(), SearchCondition.OP_EQUAL); 
						sr1 = logicFkReturnService.findItemListByExample(scs2);  //查找此物料的历史退款记录
						if(sr1.getRecordCount()>0){
							List<LogicFkReturnItemDO> hislist = sr1.getResults();
							LogicFkReturnItemDO hisitemdo = hislist.get(0);
							tempythk = tempythk.add(new BigDecimal(hisitemdo.getSthk().toString())); 
							wthk = new BigDecimal(li.getAmount().toString()).subtract(tempythk).doubleValue();
							ythk = tempythk.doubleValue();
						}else if(sr1.getRecordCount()==0){
							wthk = new BigDecimal(li.getAmount().toString()).subtract(tempythk).doubleValue();
							ythk = tempythk.doubleValue();
						}
					}
					li.setYthk(ythk);
					li.setWthk(wthk);
					li.setSthk(Double.parseDouble("0.0"));
					fkreturnitem.add(li);
				}
				
			 }else { //没有历史退款记录，第一次新增退款单
				for (LogicPoReturnItemDO si : poreturnitem) {
					LogicFkReturnItemDO li = new LogicFkReturnItemDO();
					li.setBatch(si.getBatch());
					li.setCode(si.getCode());
					li.setName(si.getName());
					li.setStatus(si.getState());
					li.setUnit(si.getJunit());
					li.setSpec(si.getSpec());
					li.setQuantity(si.getJreturnquantity());
					li.setTax_price(new BigDecimal(si.getPrice()==null? new Double("0.0"):si.getPrice()));
					li.setAmount(new BigDecimal(si.getPrice()==null? new Double("0.0"):si.getPrice()).multiply(new BigDecimal(si.getJreturnquantity()==null?new Double("0.0"):si.getJreturnquantity())).doubleValue());
					li.setYthk(Double.parseDouble("0.0"));
					li.setSthk(Double.parseDouble("0.0"));
					li.setWthk(li.getAmount());
					fkreturnitem.add(li);
				}
			}
		}
		SearchResult result =new SearchResult();
		result.setResults(fkreturnitem);
		result.setRecordCount(fkreturnitem.size());
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
	}

	@SuppressWarnings("unchecked")
	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		/*SearchConditions scs1 = new SearchConditions();
		scs1.addCondition("parentname", "供应商",SearchCondition.OP_EQUAL);
		scs1.setOrderBy("code");
		List<BasicCompanyDO> companyDOs = basicCompanyService.findListByExample(scs1).getResults();  */
		if (OperationFlag.ADD.equals(flag)) {// 新增单据时操作
			model.addAttribute("flag", "ADD");
			SearchConditions scs = new SearchConditions();
			scs.setOrderBy("dctime desc");
			scs.addCondition("spcode", id, SearchCondition.OP_EQUAL);
			scs.addCondition("paymentstatus", "0,1", SearchCondition.OP_IN);
			scs.addCondition("billstatus", "3", SearchCondition.OP_EQUAL);
			SearchResult sr = logicPoReturnService.findListByExample(scs);
			List<LogicPoReturnDO> poreturnlist= sr.getResults();
			model.addAttribute("poreturnlist", poreturnlist);
			 model.addAttribute("xx", 1);
			 model.addAttribute("pid", id);
			
			 //查询付款方式
			 SearchConditions scs2 = new SearchConditions();
			 scs2.setRemovedProperty(null);
			 SearchResult result1 = basicModePaymentService.findListByExample(scs2);
			 List<BasicModePaymentDO> mp = result1.getResults();
			 model.addAttribute("payment", mp);
		} else {
			LogicFkReturnDO fkreturnDO =logicFkReturnService.findListById(id);
			List<LogicFkReturnItemDO> fkreturnitemlist=logicFkReturnService.findItemListBytkid(fkreturnDO.getId());
			model.addAttribute("fkreturn", fkreturnDO);
			model.addAttribute("flag", fkreturnDO.getBillStatus());
			model.addAttribute("fkreturnitemlist", fkreturnitemlist);
			model.addAttribute("pid", fkreturnDO.getSpCode());
			
			if(fkreturnDO.getBillStatus()==0){
				 //查询付款方式
				 SearchConditions scs2 = new SearchConditions();
				 scs2.setRemovedProperty(null);
				 SearchResult result1 = basicModePaymentService.findListByExample(scs2);
				 List<BasicModePaymentDO> mp = result1.getResults();
				 model.addAttribute("payment", mp);
				 model.addAttribute("xx", 1);
			 }
		}
	//	model.addAttribute("companyDOs", companyDOs);
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicFkReturnDO fkreturnDO =logicFkReturnService.findListById(id);
			List<LogicFkReturnItemDO> fkreturnitemlist=logicFkReturnService.findItemListBytkid(fkreturnDO.getId());
			OutJsonGrid out = new OutJsonGrid(fkreturnitemlist);
			out.printJSon(response);
		}
	}
	

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicFkReturnDO curAP, BindingResult result, Model model) throws SyBaseException, SyCodeException {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata =request.getParameter("itemdata");
		String submitFlag = request.getParameter("submitFlag");
		if(itemdata==null&&"".equals(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("付款退款单内容不能为空！");
			return bodyMap.modelMap;
		}
		try {
			if("0".equals(submitFlag)){
				curAP.setBillStatus(0);
				curAP.setRefundStatus(0);
				logicFkReturnService.fkReturnSave(request, curAP);
			}
			if("1".equals(submitFlag)){
				curAP.setBillStatus(2);
				logicFkReturnService.fkReturnCommit(request, curAP);
			}
			
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}
	

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicFkReturnDO ld=logicFkReturnService.findListById(field);
				if(ld.getId()!=null){
					ld.setRemoved(1);
					logicFkReturnService.update(ld,SessionUtil.getUser(request));
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}

	/**
	 * ligerUI树的json
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		scs.setLimitPage(false);//不分页
		hander.getWheresNotLimit(scs);
		List<BasicCompanyDO> list =basicCompanyService.find(scs);
		AjaxUtil.printJSonArr(response, JSONArray.toJSONString(list));
	}
	
	@RequestMapping(value = "/exportExcel")
	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		try {
			
			String id = request.getParameter("id");
			LogicFkReturnDO fkreturn = new LogicFkReturnDO();
			List<LogicFkReturnItemDO> lp = new ArrayList<LogicFkReturnItemDO>();
			if(!"".equals(id)&&id!=null){
				fkreturn = logicFkReturnService.findListById(id);
			}
			if(fkreturn.getId()!=null){
				lp = logicFkReturnService.findItemListBytkid(fkreturn.getId());
			}
				request.setAttribute("fkreturn", fkreturn);
				request.setAttribute("lp", lp);
				
				response.setContentType("application/vnd.ms-excel");
				response.setHeader("Content-disposition", "attachment;filename=" + fkreturn.getTkCode() + ".xls");
			
				RequestDispatcher dispatcher = request.getRequestDispatcher("/views/printer/FkReturnPrint.jsp");
			
				dispatcher.forward(request, response);
			
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}